import yaml
from configs.setting import FILE_PATH
import os
from unit_tools.log_utils.recordlog import logs


def read_yaml(yaml_path):
    """
    读取yaml文件
    :param yaml_path: 文件路径
    :return:
    """
    try:
        testcase_list = []
        with open(yaml_path, 'r', encoding='utf-8') as file:
            data = yaml.safe_load(file)
            # 处理一个yaml文件多条用例的测试场景
            if len(data) <= 1:
                yaml_data = data[0]
                base_info = yaml_data.get('baseInfo')
                for ts in yaml_data.get('testCase'):
                    params = [base_info, ts]
                    testcase_list.append(params)
                return testcase_list

            else:
                return data
    except UnicodeDecodeError:
        logs.error(f"{yaml_path}文件编码格式错误，--尝试使用utf-8去解码YAML文件发送错误，请确保你的yaml文件是utf-8编码格式")
    except yaml.YAMLError as e:
        logs.error(f"读取{yaml_path}文件时出现格式异常，原因是:{e}")
    except Exception as e:
        logs.error(f"读取{yaml_path}文件时出现异常，原因是:{e}")


def write_yaml(value):
    """
    yaml文件数据写入
    :param value:写入的数据，必须是字典类型
    :return:
    """
    file_path = FILE_PATH['extract']
    # print(f"写入的文件路径为{file_path}")
    # 如果文件不存在，则创建文件
    if not os.path.exists(file_path):
        with open(file_path, 'w', encoding='utf-8'):
            pass
    # 下面是写入的操作
    file = None
    try:
        file = open(file_path, 'a', encoding='utf-8')
        if isinstance(value, dict):  # 如果value是字典类型，则写入
            write_data = yaml.dump(value, allow_unicode=True,
                                   sort_keys=False)  # allow_unicode=True表示写入的参数可以为中文,sort_keys=False可以不按顺序写入
            file.write(write_data)
        else:
            logs.warning(f"写入{file_path}文件时，value参数必须是字典类型")
    except Exception as e:
        logs.error(f"写入{file_path}文件时出现异常，原因是:{e}")
    finally:
        file.close()


def clear_yaml():
    """
    专门清空extract.yaml文件数据
    :return:
    """
    file_path = FILE_PATH['extract']
    with open(file_path, 'w', encoding='utf-8') as f:
        f.truncate()


def get_extract_yaml(node_name, sub_node_name=None):
    """
    用于获取全局extract.yaml数据的方法
    :param node_name: 第一级key值
    :param sub_node_name: 下级key值
    :return:
    """
    file_path = FILE_PATH['extract']
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            extract_data = yaml.safe_load(file)
            if sub_node_name is None:
                return extract_data[node_name]
            else:
                return extract_data.get(node_name, {}).get(sub_node_name)
    except yaml.YAMLError as e:
        logs.error(f"读取{file_path}文件时出现格式异常，原因是:{e}")
    except Exception as e:
        logs.error(f"读取{file_path}文件时出现异常，原因是:{e}")


# 调试一下
if __name__ == '__main__':
    res = read_yaml('../../testcase/login/login.yaml')  # 一个点表示当前文件，一个点加一个斜杠表示当前文件所在目录，两个点加一个斜杠表示当前文件的上级目录
